import React from 'react';
import 'ol/ol.css';
import 'ol-ext/dist/ol-ext.css';
import AnimatedCluster from 'ol-ext/layer/AnimatedCluster';
import ConvexHull from 'ol-ext/geom/ConvexHull';
import Hover from 'ol-ext/interaction/Hover';
import Feature from 'ol/Feature';
import {Style,Stroke,Fill,Text,Circle,Icon} from 'ol/style.js';
import {Cluster,Vector as VectorSource} from 'ol/source';
import {Vector as VectorLayer} from 'ol/layer';
import {Point,Polygon} from 'ol/geom';
import Goverlay from "@/utils/HshMap/Goverlay";
import Glayers from "@/utils/HshMap/Glayers";
import Gstyle from "@/utils/HshMap/Gstyle";

class GclusterConvexhul {
  constructor(target) {
  }
  // Style for the clusters
  getStyle = (feature, resolution) => {
    var styleCache = {};
    var size = 0;
    for (let i = 0; i < feature.get('features').length; i++) {
      size += feature.get('features')[i].values_.total_n ? feature.get('features')[i].values_.total_n : 0;
    }
    var style = styleCache[size];
    if (!style) {
      var color1 = "rgba(255, 0, 0,0.6)";
      var color2 = "rgba(255, 0, 0,0.8)";
      var i=0,j = size;
      while(j >= i){
        j = j/10;
        i++;
      }
      switch (i) {
        case 1:
          color1 = "rgba(0, 255, 0,0.6)";
          color2 = "rgba(0, 255, 0,0.8)";
          break;
        case 2:
          color1 = "rgba(199,255,17,0.6)";
          color2 = "rgba(199,255,17,0.8)";
          break;
        case 3:
          color1 = "rgba(255, 255, 0,0.6)";
          color2 = "rgba(255, 255, 0,0.8)";
          break;
        case 4:
          color1 = "rgba(255,85,20,0.6)";
          color2 = "rgba(255,85,20,0.8)";
          break;
        case 5:
          color1 = "rgba(255, 0, 0,0.6)";
          color2 = "rgba(255, 0, 0,0.8)";
          break;
        default:
          break;
      }

      var radius = Math.max(8, Math.min(size*0.75, 20));
      style = styleCache[size] =
        [ new Style(
          {	image: new Circle(
              {	radius: radius+2,
                stroke: new Stroke(
                  {	color: color1,
                    width: 4
                  })
              })
          }),
          new Style(
            {	image: new Circle(
                {	radius: radius,
                  fill: new Fill(
                    {	color: color2
                    })
                }),
              text: new Text(
                {	text: size.toString(),
                  fill: new Fill(
                    {	color: '#000'
                    })
                })
            })
        ];
    }
    return style;
  }

  removeLayer = (map, layerName) => {
    if (map.getLayers().getArray()) {
      for (let i = 0; i < map.getLayers().getArray().length; i++) {
        if (map.getLayers().getArray()[i].values_.id == layerName) {
          map.getLayers().getArray()[i].getSource().clear();
          map.removeLayer(map.getLayers().getArray()[i]);
        }
      }
    }
  }


  clusterLayerFun = (dispatch, map,birdsInfo,birdTypeStr,startDateStr,endDateStr,layerType) => {
    //清除上次图层
   this.removeLayer(map,'birds');
    this.removeLayer(map,'clusterName');
    var  where = ' status_cd=1 '
      + ' and type = ' + birdTypeStr
      + " and created_dt >= date '" + startDateStr + "' and created_dt < date '" + endDateStr + "'" ;
    var source = new Glayers().queryVectorSource('birdsProject/arcgisFeatureServerQuery',dispatch,where,layerType,4326);
    var styleBirds = Gstyle.styleBirdsDictionary(birdsInfo);
    var birdsVector = new VectorLayer({
      // zIndex: 100,
      source: source,
      style: function(feature) {
        var classify = feature.getProperties().bird_type;
        return styleBirds[classify];
      }
    });
    birdsVector.set('id', 'birds');
    map.addLayer(birdsVector);

    // Cluster Source
    var clusterSource = new Cluster({
      distance: 100,
      source: source
    });
    // Animated cluster layer
    var clusterLayer = new AnimatedCluster(
      {
        name: 'Cluster',
        source: clusterSource,
        style: this.getStyle
      });
    clusterLayer.set('id','clusterName');
    map.addLayer(clusterLayer);
    // Add over interaction that draw hull in a layer
    var vector = new VectorLayer({source: new VectorSource()})
    vector.setMap(map);
    //overlay
    var overlay = null;
    var hover = new Hover({
      cursor: "pointer", layerFilter: function (l) {
        return l === clusterLayer;
      }
    });
    map.addInteraction(hover);
    hover.on("enter", function (e) {
      if (overlay) {
        overlay.setPosition(undefined);
        overlay = null;
      }
      var h = e.feature.get("convexHull");
      if (!h) {
        var cluster = e.feature.get("features");
        //计算数组中某个元素重复出现的个数
        var obj = {};
        // calculate convex hull
        if (cluster && cluster.length) {
          var c = [];
          for (var i = 0, f; f = cluster[i]; i++) {
            c.push(f.getGeometry().getCoordinates());
            // var birdName = birdsInfo[f.getProperties().bird_type];
            //字典类型变更为字典名称
            var birdName = f.getProperties().bird_type;
            var total = f.getProperties().total_n ? f.getProperties().total_n : 0;
            obj[birdName] = (obj[birdName] + total) || total;
          }
          h = new ConvexHull(c);
          e.feature.get("convexHull", h);
        }
        //overlay
        var time = startDateStr + ' ~ ' + endDateStr;
        var pupupProperties = {'统计时间段': time};
        for (var key in obj) {
          pupupProperties[key] = obj[key] + '只';
        }
        let coodinate = e.coordinate;
        overlay = Goverlay.getOverlay_default('hover', coodinate, 1, pupupProperties);
        map.addOverlay(overlay);
      }
      vector.getSource().clear();
      if (h.length > 2) vector.getSource().addFeature(new Feature(new Polygon([h])));
    });
    var self = this;
    hover.on("leave", function (e) {
      vector.getSource().clear();
      if (overlay) {
        overlay.setPosition(undefined);
        overlay = null;
      }
    });
  }

}
export default GclusterConvexhul;
